import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'
import { GlobalStore } from '@/store'
import { ResultData } from './interface'
import { ResultEnum } from '@/enums/httpEnum'
import { ElMessage } from 'element-plus'
// const axiosCanceler = new axiosCanceler()

const config = {
  // 默认地址请求地址，可在 .env 开头文件中修改
  baseURL: '/api',
  // 设置超时时间（10s）
  timeout: 60000,
  // 跨域时候允许携带凭证
  withCredentials: true
}

class RequestHttp {
  service: AxiosInstance
  public constructor(config: AxiosRequestConfig) {
    this.service = axios.create(config)
    // 请求拦截器
    this.service.interceptors.request.use((config: AxiosRequestConfig) => {
      console.log(config.headers)
      if (config.headers) {
        const globalStore = GlobalStore()
        const token: string = globalStore.token
        if (token) {
          config.headers['x-access-token'] = token
        }
      }
      return config
    })
    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        const { data, config } = response
        // return response
        if (data.code && data.code !== ResultEnum.SUCCESS) {
          ElMessage.error(data.msg)
          return Promise.reject(data)
        }
        // * 成功请求（在页面上除非特殊情况，否则不用处理失败逻辑）
        return data
      },
      (error: AxiosError) => {
        return Promise.reject(error)
      }
    )
  }
  // * 常用请求方法封装
  get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    return this.service.get(url, { params, ..._object })
  }
  post<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    return this.service.post(url, params, _object)
  }
  put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    return this.service.put(url, params, _object)
  }
  delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
    return this.service.delete(url, { params, ..._object })
  }
}

export default new RequestHttp(config)
